/**
 * 面试题05：替换空格
 */
public class Offer_05 {
    /**
     * 方法三：字符数组
     */
    public String replaceSpace(String s) {
        int len = s.length();
        char[] arr = new char[len * 3];
        int size = 0;
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            if (ch == ' ') {
                arr[size++] = '%';
                arr[size++] = '2';
                arr[size++] = '0';
            } else {
                arr[size++] = ch;
            }
        }
        return new String(arr, 0, size);
    }

    /**
     * 方法二：StringBuilder
     */
    public String replaceSpace2(String s) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == ' ') {
                builder.append("%20");
            } else {
                builder.append(ch);
            }
        }
        return builder.toString();
    }

    /**
     * 方法一：库函数（面试会被打吧）
     */
    public String replaceSpace1(String s) {
        return s.replace(" ", "%20");
    }

    public static void main(String[] args) {
        Offer_05 solution = new Offer_05();
        String s = "We are happy.";
        String ans = solution.replaceSpace(s);
        System.out.println(ans);
    }
}
